#include "includes.h"
#include <stdio.h>
#include <stdlib.h>
#include "init.h"
#include "reader.h"

static double num_jobs = 0;/*Total number of jobs seen so far*/
static long int total_completion_time = 0;/*Total of how long each process takes to complete*/
static long int max_completion_time = 0;/*Longest to complete*/
static long int min_completion_time = MAXVAL;/*Shortest to complete, Use maxval to initialize*/
static double throughput = 0;/*Throughput, jobs per second*/
static long int total_run_time = 0;/*Total time the clock has run*/
static double avg_completion_time = 0;/*Avg comp time stat*/
static long  int utilization = 0;/*Total time spent doing useful calculations*/
static double percent_utilization = 0;/*Utilization given as a percentage*/


void perf_handle_proc(struct proc_info* proc)
{
	
	long int runtime;
	/*Get the total runtime of process*/
	runtime = (proc->finish_time - proc->arrival_time);

	/*Update variables for calculations below*/
	num_jobs = num_jobs + 1;
	total_run_time = proc->finish_time;
	total_completion_time = total_completion_time + runtime;
	
	
	/*Calculate Throughput Converted To Seconds*/
	throughput = (num_jobs / (total_run_time/1000));
	

	/*Check if finished process is min*/
	if( runtime < min_completion_time)
	{
		min_completion_time = runtime;
	}
	/*Check if completed process is max*/
	if( runtime > max_completion_time)
	{
		max_completion_time = runtime;
	}

	/* Freeing up data */
	free(proc);

	return;
	
}


void increment_cpu_time(long t)
{
	utilization = utilization + t;
	return;
}

void print_stats()
{ 
	/*Calculate new utlization percentage*/
	percent_utilization = (100.0*utilization)/clock_time;
	
	/*Calculate Average Completion Time */
	avg_completion_time = total_completion_time / num_jobs;

	
	printf("Minimum Completion Time: %g  Seconds \n", min_completion_time/1000.0);
	printf("Maximum Completion Time: %li Seconds \n", max_completion_time/1000);
	printf("Average Completetion Time: %g Seconds \n", avg_completion_time/1000.0);
	printf("Throughput: %g \n", throughput);
	printf("Total Utilization: %li \n",utilization);
	printf("Percent Utilization: %g Percent\n", percent_utilization);

	/* Free up malloc'd data */
	scheduler_close();
	reader_close();

	return;
}
